package com.dzt.cloudreader.network;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.dzt.cloudreader.constant.ConstantsImageUrl;
import com.dzt.cloudreader.model.GankIoDayBean;
import com.dzt.cloudreader.model.GankIoDayBean.ResultsBean.AndroidBean;
import com.dzt.cloudreader.mvp.MvpPresenter;
import com.dzt.cloudreader.mvp.MvpView;
import com.dzt.cloudreader.utils.JPreferenceKit;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by M02323 on 2017/12/26.
 */

public class GankIoDayPresenter implements MvpPresenter {
	private static final String HOME_ONE = "home_one";
	private static final String HOME_TWO = "home_two";
	private static final String HOME_SIX = "home_six";

	private DataManager manager;
	private CompositeSubscription mCompositeSubscription;
	private Context mContext;
	private GankIoDayView dayView;
	private List<List<AndroidBean>> lists;
	private JPreferenceKit preferenceKit;

	public GankIoDayPresenter(Context mContext) {
		this.mContext = mContext;
	}

	@Override
	public void onCreate() {
		manager = DataManager.getInstance();
		mCompositeSubscription = new CompositeSubscription();
		preferenceKit = JPreferenceKit.getInstance();
	}

	@Override
	public void onStart() {

	}

	@Override
	public void onStop() {

	}

	@Override
	public void onDestroy() {
		if (mCompositeSubscription.hasSubscriptions()) {
			mCompositeSubscription.unsubscribe();
		}
	}

	@Override
	public void attachView(MvpView view) {
		dayView = (GankIoDayView) view;
	}

	@Override
	public void attachIncomingIntent(Intent intent) {

	}

	public void getGankIoDay(String year, String month, String day) {
		preferenceKit.setStringValue(HOME_ONE, "");
		preferenceKit.setStringValue(HOME_TWO, "");
		preferenceKit.setStringValue(HOME_SIX, "");
		Func1<GankIoDayBean, Observable<List<List<AndroidBean>>>> func1 = new Func1<GankIoDayBean, Observable<List<List<AndroidBean>>>>() {
			@Override
			public Observable<List<List<AndroidBean>>> call(GankIoDayBean gankIoDayBean) {
				List<List<AndroidBean>> lists = new ArrayList<>();
				GankIoDayBean.ResultsBean results = gankIoDayBean.getResults();
				if (results.getAndroid() != null && results.getAndroid().size() > 0) {
					addUrlList(lists, results.getAndroid(), "Android");
				}
				if (results.getWelfare() != null && results.getWelfare().size() > 0) {
					addUrlList(lists, results.getWelfare(), "福利");
				}
				if (results.getIOS() != null && results.getIOS().size() > 0) {
					addUrlList(lists, results.getIOS(), "IOS");
				}
				if (results.getRestMovie() != null && results.getRestMovie().size() > 0) {
					addUrlList(lists, results.getRestMovie(), "休息视频");
				}
				if (results.getResource() != null && results.getResource().size() > 0) {
					addUrlList(lists, results.getResource(), "拓展资源");
				}
				if (results.getRecommend() != null && results.getRecommend().size() > 0) {
					addUrlList(lists, results.getRecommend(), "瞎推荐");
				}
				if (results.getFront() != null && results.getFront().size() > 0) {
					addUrlList(lists, results.getFront(), "前端");
				}
				if (results.getApp() != null && results.getApp().size() > 0) {
					addUrlList(lists, results.getApp(), "App");
				}

				return Observable.just(lists);
			}
		};

		Observer<List<List<AndroidBean>>> observer = new Observer<List<List<AndroidBean>>>() {
			@Override
			public void onCompleted() {
				if (lists != null) {
					dayView.onSuccess(lists);
				}
			}

			@Override
			public void onError(Throwable e) {
				e.printStackTrace();
				dayView.onError("请求失败！！");
			}

			@Override
			public void onNext(List<List<AndroidBean>> lists) {
				GankIoDayPresenter.this.lists = lists;
			}
		};

		mCompositeSubscription.add(manager.getGankIoDay(year, month, day)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.flatMap(func1)
				.subscribe(observer));
	}

	// subList没有实现序列化！缓存时会出错！
	private void addUrlList(List<List<AndroidBean>> lists, List<AndroidBean> arrayList, String typeTitle) {
		// title
		AndroidBean bean = new AndroidBean();
		bean.setType_title(typeTitle);
		ArrayList<AndroidBean> androidBeen = new ArrayList<>();
		androidBeen.add(bean);
		lists.add(androidBeen);

		int size = arrayList.size();
		if (size > 0 && size < 4) {
			lists.add(addUrlList(arrayList, size));
		} else if (size >= 4) {
			ArrayList<AndroidBean> list1 = new ArrayList<>();
			ArrayList<AndroidBean> list2 = new ArrayList<>();
			for (int i = 0; i < size; i++) {
				if (i < 3) {
					list1.add(getAndroidBean(arrayList, i, size));
				} else if (i < 6) {
					list2.add(getAndroidBean(arrayList, i, size));
				}
			}
			lists.add(list1);
			lists.add(list2);
		}
	}

	private AndroidBean getAndroidBean(List<AndroidBean> arrayList, int i, int androidSize) {
		AndroidBean bean = new AndroidBean();
		// 标题
		bean.setDesc(arrayList.get(i).getDesc());
		// 类型
		bean.setType(arrayList.get(i).getType());
		// 跳转链接
		bean.setUrl(arrayList.get(i).getUrl());
		// 随机图的url
		if (i < 3) {
			bean.setImage_url(ConstantsImageUrl.HOME_SIX_URLS[getRandom(3)]);//三小图
		} else if (androidSize == 4) {
			bean.setImage_url(ConstantsImageUrl.HOME_ONE_URLS[getRandom(1)]);//一图
		} else if (androidSize == 5) {
			bean.setImage_url(ConstantsImageUrl.HOME_TWO_URLS[getRandom(2)]);//两图
		} else if (androidSize >= 6) {
			bean.setImage_url(ConstantsImageUrl.HOME_SIX_URLS[getRandom(3)]);//三小图
		}
		return bean;
	}

	private List<AndroidBean> addUrlList(List<AndroidBean> arrayList, int size) {
		List<AndroidBean> tempList = new ArrayList<>();
		for (int i = 0; i < size; i++) {
			AndroidBean bean = new AndroidBean();
			// 标题
			bean.setDesc(arrayList.get(i).getDesc());
			// 类型
			bean.setType(arrayList.get(i).getType());
			// 跳转链接
			bean.setUrl(arrayList.get(i).getUrl());
			// 随机图的url
			if (size == 1) {
				bean.setImage_url(ConstantsImageUrl.HOME_ONE_URLS[getRandom(1)]);//一图
			} else if (size == 2) {
				bean.setImage_url(ConstantsImageUrl.HOME_TWO_URLS[getRandom(2)]);//两图
			} else if (size == 3) {
				bean.setImage_url(ConstantsImageUrl.HOME_SIX_URLS[getRandom(3)]);//三图
			}
			tempList.add(bean);
		}
		return tempList;
	}

	/**
	 * 取不同的随机图，在每次网络请求时重置
	 */
	private int getRandom(int type) {
		String saveWhere = null;
		int urlLength = 0;
		if (type == 1) {
			saveWhere = HOME_ONE;
			urlLength = ConstantsImageUrl.HOME_ONE_URLS.length;
		} else if (type == 2) {
			saveWhere = HOME_TWO;
			urlLength = ConstantsImageUrl.HOME_TWO_URLS.length;
		} else if (type == 3) {
			saveWhere = HOME_SIX;
			urlLength = ConstantsImageUrl.HOME_SIX_URLS.length;
		}

		String home_six = preferenceKit.getStringValue(saveWhere, "");
		if (!TextUtils.isEmpty(home_six)) {
			// 已取到的值
			String[] split = home_six.split(",");

			Random random = new Random();
			for (int j = 0; j < urlLength; j++) {
				int randomInt = random.nextInt(urlLength);

				boolean isUse = false;
				for (String aSplit : split) {
					if (!TextUtils.isEmpty(aSplit) && String.valueOf(randomInt).equals(aSplit)) {
						isUse = true;
						break;
					}
				}
				if (!isUse) {
					StringBuilder sb = new StringBuilder(home_six);
					sb.insert(0, randomInt + ",");
					preferenceKit.setStringValue(saveWhere, sb.toString());
					return randomInt;
				}
			}

		} else {
			Random random = new Random();
			int randomInt = random.nextInt(urlLength);
			preferenceKit.setStringValue(saveWhere, randomInt + ",");
			return randomInt;
		}
		return 0;
	}
}
